// DOM元素
const elements = {
  noLinksMessage: document.getElementById('no-links-message'),
  linksList: document.getElementById('links-list'),
  clearAllBtn: document.getElementById('clear-all-btn'),
  helpBtn: document.getElementById('help-btn'),
  settingsBtn: document.getElementById('settings-btn'),
  toast: document.getElementById('toast')
};

// 当前设置
let currentSettings = {};

// 初始化
async function initialize() {
  // 加载设置
  await loadSettings();
  
  // 加载链接
  await loadLinks();
  
  // 添加事件监听器
  addEventListeners();
}

// 加载设置
async function loadSettings() {
  try {
    const defaultSettings = {
      notifications: {
        enabled: true,
        timeout: 5000
      },
      player: {
        useCustom: false,
        defaultPlayer: 'https://m3u8play.com/?url=',
        customPlayerUrl: ''
      },
      downloader: {
        useCustom: false,
        defaultDownloader: 'https://tools.thatwind.com/tool/m3u8downloader#',
        customDownloaderUrl: '',
        autoOpen: false
      },
      filters: {
        enabled: false,
        rules: []
      },
      storage: {
        autoClear: false,
        maxItems: 100,
        clearAfterDays: 7
      }
    };
    
    const result = await chrome.storage.sync.get({ settings: defaultSettings });
    currentSettings = result.settings;
  } catch (error) {
    console.error('加载设置失败:', error);
    showToast('加载设置失败');
  }
}

// 加载链接
async function loadLinks() {
  try {
    const result = await chrome.storage.local.get({ m3u8Links: [] });
    const links = result.m3u8Links;
    
    // 更新清除按钮状态
    elements.clearAllBtn.disabled = links.length === 0;
    
    // 显示链接或无链接消息
    if (links.length === 0) {
      elements.noLinksMessage.classList.remove('hidden');
      elements.linksList.classList.add('hidden');
    } else {
      elements.noLinksMessage.classList.add('hidden');
      elements.linksList.classList.remove('hidden');
      
      // 渲染链接列表
      renderLinks(links);
    }
  } catch (error) {
    console.error('加载链接失败:', error);
    showToast('加载链接失败');
  }
}

// 渲染链接列表
function renderLinks(links) {
  // 清空链接列表
  elements.linksList.innerHTML = '';
  
  // 按时间排序，最新的在前面
  links.sort((a, b) => b.timestamp - a.timestamp);
  
  // 添加链接项
  links.forEach(link => {
    const linkItem = createLinkItem(link);
    elements.linksList.appendChild(linkItem);
  });
}

// 创建链接项
function createLinkItem(link) {
  const linkItem = document.createElement('div');
  linkItem.className = 'link-item';
  linkItem.dataset.url = link.url;
  
  // 格式化时间
  const date = new Date(link.timestamp);
  const formattedDate = formatDate(date);
  
  // 截断URL，最多显示50个字符
  const displayUrl = link.url.length > 50 ? link.url.substring(0, 47) + '...' : link.url;
  
  // 创建链接项内容
  linkItem.innerHTML = `
    <div class="link-info">
      <div class="link-url" title="${link.url}">${displayUrl}</div>
      <div class="link-meta">
        <div class="link-page" title="${link.pageTitle || '未知页面'}">${link.pageTitle || '未知页面'}</div>
        <div class="link-time">${formattedDate}</div>
      </div>
    </div>
    <div class="link-actions">
      <button class="action-btn copy-btn" title="复制链接">
        <svg xmlns="http://www.w3.org/2000/svg" height="18" viewBox="0 0 24 24" width="18">
          <path d="M0 0h24v24H0z" fill="none"/>
          <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
        </svg>
      </button>
      <button class="action-btn play-btn" title="播放视频">
        <svg xmlns="http://www.w3.org/2000/svg" height="18" viewBox="0 0 24 24" width="18">
          <path d="M0 0h24v24H0z" fill="none"/>
          <path d="M8 5v14l11-7z"/>
        </svg>
      </button>
      <button class="action-btn download-btn" title="下载视频">
        <svg xmlns="http://www.w3.org/2000/svg" height="18" viewBox="0 0 24 24" width="18">
          <path d="M0 0h24v24H0z" fill="none"/>
          <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
        </svg>
      </button>
      <button class="action-btn delete-btn" title="删除链接">
        <svg xmlns="http://www.w3.org/2000/svg" height="18" viewBox="0 0 24 24" width="18">
          <path d="M0 0h24v24H0z" fill="none"/>
          <path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
        </svg>
      </button>
    </div>
  `;
  
  // 添加事件监听器
  const copyBtn = linkItem.querySelector('.copy-btn');
  const playBtn = linkItem.querySelector('.play-btn');
  const downloadBtn = linkItem.querySelector('.download-btn');
  const deleteBtn = linkItem.querySelector('.delete-btn');
  
  // 复制链接
  copyBtn.addEventListener('click', () => {
    copyToClipboard(link.url);
    showToast('链接已复制到剪贴板');
  });
  
  // 播放视频
  playBtn.addEventListener('click', () => {
    openPlayer(link.url);
  });
  
  // 下载视频
  downloadBtn.addEventListener('click', () => {
    openDownloader(link.url);
  });
  
  // 删除链接
  deleteBtn.addEventListener('click', () => {
    deleteLink(link.url);
  });
  
  return linkItem;
}

// 添加事件监听器
function addEventListeners() {
  // 清除所有链接
  elements.clearAllBtn.addEventListener('click', clearAllLinks);
  
  // 打开帮助页面
  elements.helpBtn.addEventListener('click', () => {
    chrome.tabs.create({ url: 'help.html' });
  });
  
  // 打开设置页面
  elements.settingsBtn.addEventListener('click', () => {
    chrome.tabs.create({ url: 'options.html' });
  });
}

// 复制到剪贴板
function copyToClipboard(text) {
  navigator.clipboard.writeText(text).catch(error => {
    console.error('复制到剪贴板失败:', error);
    
    // 回退方法
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    document.body.removeChild(textarea);
  });
}

// 打开播放器
function openPlayer(url) {
  const playerUrl = currentSettings.player.useCustom && currentSettings.player.customPlayerUrl
    ? currentSettings.player.customPlayerUrl.replace('{url}', encodeURIComponent(url))
    : currentSettings.player.defaultPlayer + encodeURIComponent(url);
  
  chrome.tabs.create({ url: playerUrl });
}

// 打开下载器
function openDownloader(url) {
  const downloaderUrl = currentSettings.downloader.useCustom && currentSettings.downloader.customDownloaderUrl
    ? currentSettings.downloader.customDownloaderUrl.replace('{url}', encodeURIComponent(url))
    : currentSettings.downloader.defaultDownloader + encodeURIComponent(url);
  
  chrome.tabs.create({ url: downloaderUrl });
}

// 删除链接
async function deleteLink(url) {
  try {
    // 获取当前链接
    const result = await chrome.storage.local.get({ m3u8Links: [] });
    let links = result.m3u8Links;
    
    // 过滤掉要删除的链接
    links = links.filter(link => link.url !== url);
    
    // 保存更新后的链接
    await chrome.storage.local.set({ m3u8Links: links });
    
    // 更新徽章
    chrome.runtime.sendMessage({ action: 'updateBadge' });
    
    // 重新加载链接
    await loadLinks();
    
    showToast('链接已删除');
  } catch (error) {
    console.error('删除链接失败:', error);
    showToast('删除链接失败');
  }
}

// 清除所有链接
async function clearAllLinks() {
  if (confirm('确定要清除所有链接吗？此操作不可撤销。')) {
    try {
      // 清空链接
      await chrome.storage.local.set({ m3u8Links: [] });
      
      // 更新徽章
      chrome.runtime.sendMessage({ action: 'updateBadge' });
      
      // 重新加载链接
      await loadLinks();
      
      showToast('所有链接已清除');
    } catch (error) {
      console.error('清除链接失败:', error);
      showToast('清除链接失败');
    }
  }
}

// 格式化日期
function formatDate(date) {
  const now = new Date();
  const diff = now - date;
  
  // 不到1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 不到1小时
  if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000));
    return `${minutes}分钟前`;
  }
  
  // 不到24小时
  if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000));
    return `${hours}小时前`;
  }
  
  // 不到7天
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000));
    return `${days}天前`;
  }
  
  // 其他情况，显示完整日期
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 显示提示消息
function showToast(message) {
  elements.toast.textContent = message;
  elements.toast.classList.add('show');
  
  setTimeout(() => {
    elements.toast.classList.remove('show');
  }, 3000);
}

// 当页面加载完成时初始化
document.addEventListener('DOMContentLoaded', initialize);